package com.pansoft.resmanager;

import java.io.UnsupportedEncodingException;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import android.util.Base64;

/**
 * 对字符串进行加密和解密
 * @author yanxh
 *
 */
public class Des3 {
	public static byte[] ivData = { 1, 2, 3, 4, 5, 6, 7, 8 }; 
	//密钥
	public static byte[] key=Base64.decode("28956778443231900876123786545676", Base64.DEFAULT);
	/**
	 * 
	 * @param data 原始数据
	 * @return     加密后的字符串
	 * @throws Exception
	 */
    public static byte[] des3EncodeCBC(byte[] data)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(ivData);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }
    /**
     * 
     * @param data 加密后的数据
     * @return     原始数据
     * @throws Exception
     */
    public static byte[] des3DecodeCBC( byte[] data)
            throws Exception {
        Key deskey = null;
        DESedeKeySpec spec = new DESedeKeySpec(key);
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede" + "/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(ivData);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
        byte[] bOut = cipher.doFinal(data);
        return bOut;
    }
    /**
     * 加密和解密的使用方式 demo
     */
    public  static void test(){
    	//原始数据
    	String mainStr = "达达ABCacb123";
    	//原始数据转byte
    	byte[] data;
    	try {
    		data = mainStr.getBytes("UTF-8");
    		System.out.println("原始数据:" + mainStr);
    		//加密后的byte[]
    		byte[] encodeByte_ECB = des3EncodeCBC(data);
    		//加密后的String   需把加密的byte[]转base64
    		String encodeString_ECB =Base64.encodeToString(encodeByte_ECB, Base64.DEFAULT);
    		System.out.println("加密的数据是:" + encodeString_ECB);
    		//解密后的原始byte[] 需把加密后的byte[]转bass64
    		byte[] decodeByteMain_ECB=Base64.decode(encodeString_ECB, Base64.DEFAULT);
    		//解密后的byte[]
    		byte[] decodeByte_ECB = des3DecodeCBC( decodeByteMain_ECB);
    		//解密后的String
    		String decodeString_ECB;
    		decodeString_ECB = new String(decodeByte_ECB, "UTF-8");
    		System.out.println("解密后的数据是:" + decodeString_ECB);
    	} catch (UnsupportedEncodingException e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}
    }

}
